﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceApplication.Service;
using CommonLibrary.Common;
using CommonLibrary.DataModel.Form;
using System.Xml.Linq;
using Bukovics.Workflow.Hosting;
using System.IO;
using System.Xml;
using System.Workflow.Runtime;
using System.Data.SqlClient;
using CommonLibrary.DataModel.WorkFlow;
using System.Workflow.Activities;
using ServiceApplication.Service.WorkFlow;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Basic;
using CommonLibrary.Wf.InterFace;
using System.Data;
using System.Workflow.ComponentModel;
using System.Workflow.Activities.Rules;
using CommonLibrary.Wf.Common;

namespace AspWebTest
{
    public partial class WfwithForm : System.Web.UI.Page
    {
        FormService formService = new FormService();
        SerializeDesigner designer = new SerializeDesigner();
        WorkFlowService workFlowService = new WorkFlowService();
        BasicService basicService = new BasicService();
        string formdefine;
        //int[] nextClr; 用clrinfo类来存储
        WfClrxxInfo nextClrInfo=new WfClrxxInfo();
        int tempid;

        protected void Page_Load(object sender, EventArgs e)
        {
            InitTree();
            tempid = int.Parse(Request["wftempid"]);
            TreeView1.SelectedNodeChanged += new EventHandler(TreeView1_SelectedNodeChanged);
            int formid;
            if (int.TryParse(Request.QueryString["formid"].ToString(), out formid))
            {
                FormEntity formEntity = formService.QueryFormEntity(formid);
                if (formEntity != null)
                {
                    XElement xml = XElement.Load(Server.MapPath("~/uploads/" + formEntity.location));

                    //返回
                    formdefine = designer.DeserializeXmlToWeb(xml);
                    //Response.Write(formdefine);

                }
            }

            #region 获取下一步处理人类型
            WfClrxxInfo nextClz = workFlowService.getClrxxByFirstNext(
                (Application[MyWorkHelpr.WorkflowStaticTemplate] as Dictionary<int, StateMachineWorkflowInstance>), tempid);

            if (nextClz != null)
            {
                if (nextClz.clzType == TaskClrType.由上一步处理人指定.ToString())
                {
                    TreeView1.Visible = true;
                }
                else
                {
                    TreeView1.Visible = false;
                    nextClrInfo = nextClz;
                }
            }
            #endregion
        }
        public string getDefine()
        {
            return formdefine;
        }

        protected void Button_ok_Click(object sender, EventArgs e)
        {
            //WorkflowInstanceWrapper wfiw = MyWorkHelpr._workflowManager.StartWorkflow(typeof(给叶老看看), null);
            //MessageBox.Show(this,Request["txt_je"]);
            string a = Request.Form["text1"];
        }

        protected void Button_oksend_Click(object sender, EventArgs e)
        {
            if (TextBox1_wfname.Text == "")
            {
                MessageBox.Show(this, "请填写流程名称");
                return;
            }
            #region 数据库操作: 查询wftemplate信息
            //string sql = "SELECT wftemplate_id,wftemplate_name,wfdefinition,wfrule,wflayout FROM OAonline.dbo.wf_template where wftemplate_id='" + Request["wftempid"] + "'";
            //string[][] result = CommonLibrary.DB.DBExecuteUtil.querySqlArray(sql);
            //TextReader t1 = new StringReader(result[0][2]);
            //TextReader t2 = new StringReader(result[0][3]);
            //XmlReader reader = XmlReader.Create(t1);
            //XmlReader reader2 = XmlReader.Create(t2);
            #endregion
            #region 页面操作: 取值,传参
            List<FormFieldEntity> ffeList = new FormService().QueryFormFieldEntitys(int.Parse(Request["formid"].ToString()), "text");//表单字段实体List
            List<WfInsvalueEntity> wivList = new List<WfInsvalueEntity>();//工作流实例值List
            //Dictionary<string, object> dics = new Dictionary<string, object>();
            Dictionary<string, string> dicsp = new Dictionary<string, string>();
            #region 获取页面上的工作流实例值(wivList)
            foreach (FormFieldEntity item in ffeList)
            {
                wivList.Add(new WfInsvalueEntity()
                {
                    task_id = 0,
                    fieldName = item.name,
                    fieldType = item.fieldtype,
                    fieldValue = Request.Form[item.name],//等待小马的答复.
                });
                if (!string.IsNullOrEmpty(item.ifwfjudge))
                {
                    //dics.Add(item.ifwfjudge, Request.Form[item.name]);//将需要在wf中判断的字段存入dic中,传入启动的wf实例
                    dicsp.Add(item.ifwfjudge, Request.Form[item.name]);
                }
            }
            #endregion
            #endregion
            WorkflowRuntimeManager manager = (Application[MyWorkHelpr.WorkflowRuntimeManager] as WorkflowRuntimeManager);
            {
                manager.WorkflowRuntime.StartRuntime();
                manager.MessageEvent += delegate(
                    Object sender1, WorkflowLogEventArgs e1)
                {
                    Console.WriteLine(e1.Message);
                };

                WorkflowInstanceWrapper wfiw;

                #region 如果tree可见,获取页面上选择的下一步处理人,如果不可见，则在当页初始化的时候已赋值
                if (TreeView1.Visible == true)
                {
                    TreeNodeCollection nexts = TreeView1.CheckedNodes;
                    if (TreeView1.CheckedNodes.Count == 0)
                    {
                        MessageBox.Show(this, "请选择处理人");
                        return;
                    }
                    nextClrInfo.clrCode = new int[nexts.Count];
                    for (int i = 0; i < nexts.Count; i++)
                    {
                        UserEntity nextOne = basicService.QueryUser(int.Parse(nexts[i].Value));
                        if (nextOne.name != nexts[i].Text) MessageBox.Show(this, "出错：不存在" + nexts[i].Text);
                        nextClrInfo.clrCode[i] = nextOne.id;
                    }
                }
                #endregion
                UserEntity ue = (Session["UserEntity"] as UserEntity);
                UserEntity fqrEntity = basicService.QueryUser(ue.id);
                StartParameter sp = new StartParameter()
                    {
                        createrInfo = fqrEntity,
                        insValue = dicsp,
                        wfName = TextBox1_wfname.Text,//界面上获取,默认demo
                        nextYh = nextClrInfo.clrCode
                    };
                wfiw = workFlowService.createWorkflow(
                    manager, int.Parse(Request["wftempid"]), int.Parse(Request.QueryString["wfid"]), sp, wivList,null,"",DateTime.Now,null);
                MessageBox.Show(this, "OK");
            }
        }

        protected void Button_cancel_Click(object sender, EventArgs e)
        {

        }

        protected void Button_wfinfo_Click(object sender, EventArgs e)
        {

        }

        #region tree
        private void InitTree()
        {
            TreeView1.ShowCheckBoxes = TreeNodeTypes.Leaf;

            DataTable dt = basicService.QueryAllDepts();
            WebNodeHelp nh = new WebNodeHelp(dt, "部门编码", "部门名称", "上级编码", "部门编码=1");

            //将子node写入treeview
            foreach (var item in basicService.GetWebUserNodeList())
            {
                TreeView1.Nodes.Add(item);
            }
        }

        void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
        {
            //点击的事件处理
            //TreeNode node = TreeView1.SelectedNode;
            //UserEntity nextOne = basicService.QueryUser(int.Parse(node.Value));
            //if (nextOne.name != node.Text) return;

            //manage



            //



        }


        #region 主从表绑定
        //private void BindTree()
        //{
        //    DataSet dst = GetTreeViewData();
        //    DataRow[] rootnodes = dst.Tables["depts"].Select("supid=0");
        //    TreeView1.ShowCheckBoxes = TreeNodeTypes.All;
        //    //加载根节点
        //    foreach (DataRow masterRow in rootnodes)
        //    {
        //        TreeNode masterNode = new TreeNode((string)masterRow["name"]);
        //        TreeView1.Nodes.Add(masterNode);
        //        foreach (DataRow childRow in masterRow.GetChildRows("Children"))
        //        {
        //            TreeNode childNode = new TreeNode((string)childRow["name"]);
        //            masterNode.Expanded = false;
        //            masterNode.ChildNodes.Add(childNode);
        //        }
        //    }


        //    //加载同表中非根节点
        //    foreach (DataRow masterRow in dst.Tables["depts"].Rows)
        //    {
        //        TreeNode masterNode = new TreeNode((string)masterRow["name"]);
        //        TreeView1.Nodes.Add(masterNode);
        //        foreach (DataRow childRow in masterRow.GetChildRows("Children"))
        //        {
        //            TreeNode childNode = new TreeNode((string)childRow["name"]);
        //            masterNode.Expanded = false;
        //            masterNode.ChildNodes.Add(childNode);
        //        }
        //    }
        //}

        //private void GetChildNode(TreeNode supNode, string supId)
        //{

        //    DataRow[] drs = _dt.Select(_supId + " = " + supId);
        //    if (drs.Length == 0) return;
        //    foreach (var dr in drs)
        //    {
        //        TreeNode childNodes = new TreeNode(dr[_name].ToString());
        //        NodeTag nh = new NodeTag
        //        {
        //            Text = childNodes.Text,
        //            Value = dr[_id].ToString(),
        //            bz = string.Empty,
        //            level = 0,
        //        };
        //        childNodes.Tag = nh;
        //        GetChildNode(childNodes, (childNodes.Tag as NodeTag).Value);
        //        supNode.Nodes.Add(childNodes);
        //    }
        //}

        //private DataSet GetTreeViewData()
        //{
        //    string constring = "Data Source=.\\SQL2005;Initial Catalog=OAonline;Integrated Security=True";
        //    SqlConnection con = new SqlConnection(constring);
        //    SqlDataAdapter daprovince = new SqlDataAdapter("SELECT * FROM system_depts", con);
        //    SqlDataAdapter dacity = new SqlDataAdapter("SELECT * FROM system_users", con);
        //    DataSet ds = new DataSet();
        //    daprovince.Fill(ds, "depts");
        //    dacity.Fill(ds, "users");
        //    ds.Relations.Add("Children", ds.Tables["depts"].Columns["id"], ds.Tables["users"].Columns["dept_id"]);
        //    return ds;
        //}
        #endregion
        #endregion
    }
}
